package com.py.credit.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.ResourceManualAssociateFieldsEnum;
import com.py.credit.service.ManualAssociateService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.MapCache;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 手动关联
 * 
 * @author jicm
 * 
 */
@RestController
@RequestMapping(value = "/manualAssociate")
public class ManualAssociateController extends BaseController {

	private final static String FRONT_TABLE_ID = "manualAssociate";

	@Autowired
	private ManualAssociateService manualAssociateService;

	@Autowired
	private RemoteBaseService remoteBaseService;

	/**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(ResourceManualAssociateFieldsEnum.getOptionalColumns());
	}

	/**
	 * @api {get} /manualAssociate/getDataList.json 手动关联数据列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 手动关联
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} rootId 库id(必需)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{"data_id":22,"root_id":100000,"A000001":"金电测试3","A000002":"1234SKEM23451MDK42","table_id":200244,"dept_id":7,"A000003":"1111","A000004":"1111","A000005":"1111","A000006":"1111"}]}
	 * 
	 */
	@RequestMapping(value = "/getDataList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "rootId", defaultValue = "", required = true) int rootId, Page page,
			HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ManualAssociateController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceManualAssociateFieldsEnum.getDefaultShowColumnEN(rootId) : Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		String[] additionalColumns = { "root_id", "table_id", "dept_id", "data_id" };
		try {
			List<Map<String, Object>> tableList = manualAssociateService.getByConditionForPage(showColumns,
					additionalColumns, condition, rootId, page, userInfo);
			// 获取当前用户的部门
			RestServiceResult<Map<String, String>> depts = remoteBaseService
					.getCurrentUserOfficesName(HttpServletHelper.getUserToken(request));
			if (RestServiceResult.CODE_SUCCESS != depts.getCode()) {
				result.setCode(depts.getCode());
				result.setMsg(depts.getMsg());
				return result;
			}
			Map<String, String> deptInfo = depts.getData();
			result.setCount(page.getTotalCount());
			result.setData(tableList);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请稍后再试！");
			ExceptionLogger.error("获取手动关联数据列表异常！", e.getMessage(), e);
			return result;
		}
	}

	/**
	 * @api {get} /manualAssociate/selectOne.json 查看待关联数据详情
	 * @apiName selectOne
	 * @apiVersion 0.0.1
	 * @apiGroup 手动关联
	 * 
	 * @apiParam {int} tableId 表id(必需)
	 * @apiParam {int} dataId 数据id(必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{A000001:"企业1222"
	 *                    A000002:"TY123456789" A000003:"GS12345678"
	 *                    A000004:"ZZ12345678" A000005:"SW12345678"
	 *                    A000006:"注册地址" JG_GGSY_QJDF_BJRQ:1524543132000
	 *                    JG_GGSY_QJDF_GXSJ:"备注" JG_GGSY_QJDF_JE:"10000"
	 *                    JG_GGSY_QJDF_QJSD:1524456732000
	 *                    JG_GGSY_QJDF_QJSJ:1524456732000
	 *                    JG_GGSY_QJDF_SFDW:"收费单位" JG_GGSY_QJDF_TS:"7"
	 *                    JG_GGSY_QJDF_ZT:"已经补交" JG_GGSY_QJSF_GXSJ:1524629532000
	 *                    address:null batch_Id:"EX-10000060873-1-20180427-7766"
	 *                    creditTime:1524827600000 errorMess:""
	 *                    md5:"DFD3EF061B6B698DBFB0F428BA304293" record_id:58
	 *                    status:"R" tybm:" "}]}
	 * 
	 */
	@RequestMapping(value = "/selectOne.json")
	public RestServiceResult<Map<String, Object>> selectOne(
			@RequestParam(value = "tableId", defaultValue = "", required = true) int tableId,
			@RequestParam(value = "dataId", defaultValue = "", required = true) int dataId) {

		Map<String, Object> data = manualAssociateService.selectOne(tableId, dataId);

		return new RestServiceResult<Map<String, Object>>(data);

	}

	/**
	 * @api {get} /manualAssociate/selectAssociate.json 查看待关联数据主体信息
	 * @apiName selectAssociate
	 * @apiVersion 0.0.1
	 * @apiGroup 手动关联
	 * 
	 * @apiParam {int} rootId 库id(必需)
	 * @apiParam {int} tableId 表id(必需)
	 * @apiParam {int} dataId 数据id(必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{A000001:"企业1222"
	 *                    A000002:"TY123456789" A000003:"GS12345678"
	 *                    A000004:"ZZ12345678" A000005:"SW12345678"
	 *                    A000006:"注册地址" }]}
	 * 
	 */
	@RequestMapping(value = "/selectAssociate.json")
	public RestServiceResult<List<Map<String, Object>>> selectAssociate(
			@RequestParam(value = "rootId", defaultValue = "", required = true) int rootId,
			@RequestParam(value = "tableId", defaultValue = "", required = true) int tableId,
			@RequestParam(value = "dataId", defaultValue = "", required = true) int dataId) {
		List<Map<String, Object>> data = manualAssociateService.selectAssociate(rootId, tableId, dataId);
		return new RestServiceResult<List<Map<String, Object>>>(data);

	}

	/**
	 * @api {get} /manualAssociate/seachData.json 匹配数据列表
	 * @apiName seachDataForPage
	 * @apiVersion 0.0.1
	 * @apiGroup 手动关联
	 * 
	 * @apiParam {String} condition 选择条件(可选)
	 * @apiParam {int} rootId 库id(必需)
	 * @apiParam {String} A000001 A000001(必需)
	 * @apiParam {String} A000006 A000006(必需)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{A000001:"企业1222"
	 *                    A000002:"TY123456789" A000003:"GS12345678"
	 *                    A000004:"ZZ12345678" A000005:"SW12345678"
	 *                    A000006:"注册地址" }]}
	 * 
	 */
	@RequestMapping(value = "/seachData.json")
	public RestServiceResult<List<Map<String, Object>>> seachDataForPage(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "rootId", defaultValue = "", required = true) int rootId,
			@RequestParam(value = "A000001", defaultValue = "", required = true) String A000001,
			@RequestParam(value = "A000002", defaultValue = "", required = true) String A000002, 
			@RequestParam(value = "A000003", defaultValue = "", required = true) String A000003,Page page,
			HttpServletRequest request) {
		String[] additionalColumns = { "tybm" };
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ManualAssociateController#seachDataForPage", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + FRONT_TABLE_ID);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? ResourceManualAssociateFieldsEnum.getDefaultShowColumnEN(rootId) : Arrays.asList(configColumns);
		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		List<Map<String, Object>> data = manualAssociateService.seachDataByConditionForPage(showColumns,
				additionalColumns, condition, rootId, A000001, A000002,A000003, page);
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), data);

	}

	/**
	 * @api {get} /manualAssociate/updateData.json 数据关联
	 * @apiName updateData
	 * @apiVersion 0.0.1
	 * @apiGroup 手动关联
	 * 
	 * @apiParam {int} rootId 库id(必需)
	 * @apiParam {String} tybm(选择关联的数据)(必需)
	 * @apiParam {int} tableId(实际数据表的id)(必需)
	 * @apiParam {int} dataId(待关联数据的record_id)(必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":1,"data":[{}]}
	 * 
	 */
	@RequestMapping(value = "/updateData.json")
	public RestServiceResult<Object> updateData(
			@RequestParam(value = "rootId", defaultValue = "", required = true) int rootId,
			@RequestParam(value = "tybm", defaultValue = "", required = true) String tybm,
			@RequestParam(value = "tableId", defaultValue = "", required = true) int tableId,
			@RequestParam(value = "dataId", defaultValue = "", required = true) int dataId) {
		manualAssociateService.updateData(rootId, tybm, tableId, dataId);
		return new RestServiceResult<Object>();

	}
}
